#!/bin/sh

if [ $# -ne 2 ]; then
    echo "Usage: $0 /path/to/netcipher-1.2.jar /another/netcipher-1.2.jar"
    exit 1
fi

set -e
set -x

test -e "$1"
test -e "$2"

tmpdir=`mktemp -d /tmp/.compare-zips.XXXXXXXXXX`
jar1=$(basename $1)
jar2=$(basename $2)
sourcedir1=$(cd `dirname $1` && pwd)
sourcedir2=$(cd `dirname $2` && pwd)
jarname1=`echo $jar1 | sed 's,\.jar$,,'`
jarname2=`echo $jar2 | sed 's,\.jar$,,'`
dir1=$tmpdir/`echo $(dirname $1) | sed 's,[/ ],_,g'`-$jarname1
dir2=$tmpdir/`echo $(dirname $2) | sed 's,[/ ],_,g'`-$jarname2

mkdir -p $dir1
cd $dir1
unzip "$sourcedir1/$jar1"
# ignore the file path in the sum
md5sum "$sourcedir1/$jar1" | cut -d ' ' -f 1 > md5sum
sha1sum "$sourcedir1/$jar1" | cut -d ' ' -f 1 > sha1sum
sha256sum "$sourcedir1/$jar1" | cut -d ' ' -f 1 > sha256sum
# strip the full path to the zip for the comparison
unzip -l "$sourcedir1/$jar1" | sed 's,^\(Archive:\s\s*\)/.*/,\1,' > $dir1/unzip-l.txt
unzip -lv "$sourcedir1/$jar1" | sed 's,^\(Archive:\s\s*\)/.*/,\1,' > $dir1/unzip-lv.txt
zipinfo -lv "$sourcedir1/$jar1" | sed 's,^\(Archive:\s\s*\)/.*/,\1,' > $dir1/zipinfo-lv.txt
hexdump -C "$sourcedir1/$jar1" > $dir1/xxd

mkdir -p $dir2
cd $dir2
unzip "$sourcedir2/$jar2"
md5sum "$sourcedir2/$jar2" | cut -d ' ' -f 1 > md5sum
sha1sum "$sourcedir2/$jar2" | cut -d ' ' -f 1 > sha1sum
sha256sum "$sourcedir2/$jar2" | cut -d ' ' -f 1 > sha256sum
# strip the full path to the zip for the comparison
unzip -l "$sourcedir2/$jar2" | sed 's,^\(Archive:\s\s*\)/.*/,\1,' > $dir2/unzip-l.txt
unzip -lv "$sourcedir2/$jar2" | sed 's,^\(Archive:\s\s*\)/.*/,\1,' > $dir2/unzip-lv.txt
zipinfo -lv "$sourcedir2/$jar2" | sed 's,^\(Archive:\s\s*\)/.*/,\1,' > $dir2/zipinfo-lv.txt
hexdump -C "$sourcedir2/$jar2" > $dir2/xxd

if which meld > /dev/null; then
    meld $dir1 $dir2
elif which opendiff > /dev/null; then
    opendiff $dir1 $dir2
else
    echo "ERROR: meld or opendiff required for the comparison!"
fi

rm -rf $tmpdir/
